package lightswitch.code.connection;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

import javax.swing.JOptionPane;

import lightswitch.client.code.gui.MainFrame;
import lightswitch.client.code.util.StatementType;
import lightswitch.client.code.util.StringHelper;

public class DataReceivingThread extends Thread{
    private Socket socket;
    private ObjectInputStream br = null;
    private ObjectOutputStream bw = null;
    private String query=null;
    
    public DataReceivingThread(Socket socket, String query){
        this.socket=socket;
        this.query = StringHelper.NormalizeString(query);
    }
    
    public void run(){
        try {
            bw = new ObjectOutputStream(socket.getOutputStream());
            br = new ObjectInputStream(socket.getInputStream());
            //send query
            bw.writeObject(query);
            bw.flush();
            
            //receive result type
            String typeReceive = (String)br.readObject();
            if (typeReceive ==  StatementType.NOT_SUPPORT){
                JOptionPane.showMessageDialog(null, "Query statement not support", "Message", 1);
            } else if (typeReceive ==  StatementType.CLASS_NOT_FOUND){
                JOptionPane.showMessageDialog(null, "Send/Receive data error\nSystem is disconnected, reconnect later", "Message", 1);
                bw.close();
                br.close();
                socket.close();
            } else if (typeReceive ==  StatementType.IOERROR){
                JOptionPane.showMessageDialog(null, "Query statement has some errors\nSystem is disconnected, reconnect later", "Message", 1);
                bw.close();
                br.close();
                socket.close();
            } else if (typeReceive.equals(StatementType.SELECT)){
                QueryDataTransfering data = (QueryDataTransfering)br.readObject();
                ConnectionHelper.changeQueryData(data);
            } else {
                int effectedRows = (int)br.readObject();
                if (effectedRows==-2){
                    JOptionPane.showMessageDialog(null, "Query is invalid!", "Message", 1);
                    return;
                }
                String plural="";
                if (effectedRows>=2) plural="s";
                JOptionPane.showMessageDialog(null, typeReceive+" "+effectedRows+" row"+plural+" effected", "Message", 1);
            }
            
        } catch (IOException ex) {
            ConnectionHelper.clientSocket = null;
            JOptionPane.showMessageDialog(null, "Connection is lost", "Message", 1);
            return;
        } catch (ClassNotFoundException ex) {
            ConnectionHelper.clientSocket = null;
            JOptionPane.showMessageDialog(null, "Connection is lost", "Message", 1);
            return;
        }
      
    }
}
